<?php

class DiseaseService
{

    public function getEvaluateValueToPercent($value)
    {

        if ($value["value"] > $value["int_med_val_high"]) {
            $percent = 2.0 / 3 + (($value["value"] - $value["int_med_val_high"]) / ($value["ceil"] - $value["int_med_val_high"])) / 3;
        } elseif ($value["value"] > $value["int_med_val_low"]) {
            $percent = 1.0 / 3 + (($value["value"] - $value["int_med_val_low"]) / ($value["int_med_val_high"] - $value["int_med_val_low"])) / 3;
        } elseif ($value["value"] > ($value["int_med_val_low"] * 0.3)) {
            $percent = ($value["value"] / $value["int_med_val_low"]) / 3;
        } else {
            $percent = 0.1;
        }
        $ret["percent"] = ceil($percent * 100) > 93 ? 93 : ceil($percent * 100);
        $ret["low"] = 34;
        $ret["high"] = 67;
        return $ret;
    }

    /**
     *
     */
    public function getBeEvaluated($arr)
    {
        if (!isset($arr["uid"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $uid = $arr["uid"];
        //获取用户问卷和体检报告信息
        $userinfo = $this->getUserInfo($uid);
        if (is_int($userinfo)) {
            return $userinfo;
        }
        return true;
    }

    /**
     * 根据因素获取风险评估结果
     */
    public function getEvaluateListByElements($userinfo, $userReportInfo = array())
    {
        $items = array();
        try {
            //高血压
            $ret = $this->getEvaluateByElements(Disease::GAOXUEYA, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
            //冠心病
            $ret = $this->getEvaluateByElements(Disease::GUANXINBING, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
            //脑卒中
            $ret = $this->getEvaluateByElements(Disease::NAOZUZHONG, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
            //糖尿病
            $ret = $this->getEvaluateByElements(Disease::TANGNIAOBING, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
            //肺癌
            $ret = $this->getEvaluateByElements(Disease::FEIAI, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
            //胃癌
            $ret = $this->getEvaluateByElements(Disease::WEIAI, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
            //肝癌
            $ret = $this->getEvaluateByElements(Disease::GANAI, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
            //结直肠癌
            $ret = $this->getEvaluateByElements(Disease::JIEZHICHANGAI, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
            //食管癌
            $ret = $this->getEvaluateByElements(Disease::SHIGUANAI, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
//            //乳腺癌
//            $ret = $this->getEvaluateByElements(Disease::RUXIANAI, $userinfo, $userReportInfo);
//            if(is_int($ret)){
//                return $ret;
//            }
//            array_push($items, $ret);
//            //子宫颈癌
//            $ret = $this->getEvaluateByElements(Disease::ZIGONGJINGAI, $userinfo, $userReportInfo);
//            if(is_int($ret)){
//                return $ret;
//            }
//            array_push($items, $ret);
            //鼻咽癌
            $ret = $this->getEvaluateByElements(Disease::BIYANAI, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
            //膀胱癌
            $ret = $this->getEvaluateByElements(Disease::PANGGUANAI, $userinfo, $userReportInfo);
            if (is_int($ret)) {
                return $ret;
            }
            array_push($items, $ret);
        } catch (Exception $exc) {
            return JSONHelper::ERROR_SERVICE;
        }


        return $items;
    }

    public function getEvaluateListBySession()
    {
        //如果是从问卷进入，需要重置Yii::app()->session['userinfo']
//        if (Yii::app()->session['procession'] == "forward") {
        $question_arr = Yii::app()->session['question_arr'];
        $time = implode("-", $question_arr[1]['ans']);
        $time = trim($time, "-");
        $userinfo['age'] = $time;
        array_shift($question_arr);

        foreach ($question_arr as $question) {
            foreach ($question['ans'] as $key => $value) {
                $userinfo[$key] = $value;
            }
        }
        Yii::app()->session['userinfo'] = $userinfo;
//        } elseif (Yii::app()->session['procession'] == "backward") {
//            $userinfo = Yii::app()->session['userinfo'];
//        } else {
//            return JSONHelper::ERROR_ILLEGAL_REQUEST;
//        }
        $userReportInfo = array();
        $date = new CObject(array("update_at" => time()));
        $items = $this->getEvaluateListByElements($userinfo, $userReportInfo);
        if (is_int($items)) {
            return $items;
        } else {
            return array("date" => $date, "items" => $items);
        }
    }

    /**
     * 获取疾病风险评估结果
     * $_GET['uid']
     */
    public function getEvaluateList($arr)
    {
        $uid = $arr["uid"];
        //获取用户问卷和体检报告信息
        $userinfo = $this->getUserInfo($uid);
        if (is_int($userinfo)) {
            return $userinfo;
        }
        $userReportInfo = $this->getUserReportInfo($uid);
        $date = $this->getEvaluateDateTime($uid);
        $items = $this->getEvaluateListByElements($userinfo, $userReportInfo);
        if (is_int($items)) {
            return $items;
        } else {
            return array("date" => $date, "items" => $items);
        }
    }

    public function getEvaluateByElements($disid, $userinfo, $userReportInfo = array())
    {
        $dis = new Disease($disid);
        $ret = $dis->assess($userinfo, $userReportInfo);
        if ($ret === false) {
            return JSONHelper::ERROR_SERVICE;
        }
        $item["id"] = $disid;
        $item["name"] = $dis->getDisType($item["id"]);
        $item["value"] = $this->getEvaluateValueToPercent($ret);
        return $item;
    }

    /**
     * 根据用户ID，计算某个疾病评估结果
     */
    public function getEvaluateResultByElement($disid, $userinfo)
    {
        $ret = $this->getEvaluateByElements($disid, $userinfo);

        if (is_int($ret)) {
            return $ret;
        }

        $dis = new Disease($disid);
        $eles = $dis->getElements();
        if ($eles === false || count($eles) === 0) {
            return JSONHelper::ERROR_DISEASE_ELES;
        }

        //因素解析+危险因素解读+生活建议
        $yinsu = $dis->yinsujiedu($userinfo, array(), $eles);


        $ret["yinsu"] = $yinsu;
        return $ret;
    }

    /**
     * 根据用户ID，计算某个疾病风险值
     * uid $arr
     */
    public function getEvaluateById($arr)
    {
        if (!isset($arr["disid"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $dis = new Disease($arr["disid"]);
        $eles = $dis->getElements();
        if ($eles === false || count($eles) === 0) {
            return JSONHelper::ERROR_DISEASE_ELES;
        }

        $userinfo = (isset($arr['uid']) && !empty($arr['uid'])) ? $this->getUserInfo($arr["uid"]) : Yii::app()->session['userinfo'];
        if (is_int($userinfo)) {
            return $userinfo;
        }

        $reportInfo = (isset($arr['uid']) && !empty($arr['uid'])) ? $this->getUserReportInfo($arr["uid"]) : array();
        $ret = $dis->assess($userinfo, $reportInfo);
        if ($ret === false) {
            return JSONHelper::ERROR_SERVICE;
        }

        //因素解析+危险因素解读+生活建议
        $yinsu = $dis->yinsujiedu($userinfo, $reportInfo, $eles);

        $item["id"] = $arr["disid"];
        $item["name"] = $dis->getDisType($arr["disid"]);
        $item["value"] = $this->getEvaluateValueToPercent($ret);
        $item["yinsu"] = $yinsu;
        return $item;
    }

    public function getList()
    {
        $disease_id_name_arr = array();
        $disease = EvaluateDiseaseType::model()->getDiseaseIdName();
        if ($disease == array()) {
            return JSONHelper::ERROR_NONE_DISEASE;
        }
        foreach ($disease as $item) {
            $disease_id_name_arr[] = array("id" => $item->id, "name" => $item->name);
        }
        return $disease_id_name_arr;
    }

    /**
     * 获取用户的信息，包括问卷和体检报告数据
     */
    public function getUserInfo($uid, $dis = null)
    {
        $ret = B2bUserQuestionResult::model()->findAllByAttributes(array("uid" => $uid));
//        $userinfo = EvaluateUserDiselement::model()->findByAttributes(array(
//                    "uid"=>$arr["uid"],),array("order"=>"id desc"));
        if (count($ret) == 0) {
            return JSONHelper::ERROR_EVALUATE_NOINFO;
        }
        $userinfo = array();
        foreach ($ret as $it) {
            $userinfo[$it->type] = $it->value;
        }
        //检查问卷是不是完全，不一定有必要哦
        $eles = EvaluateDiseaseElement::model()->findAllByAttributes(array("type" => EvaluateDiseaseElement::TYPEQUESTION), array("select" => "distinct field_name"
        ));

        foreach ($eles as $key => $element_name) {
            //$col = $element_name->element_name;
            //用户所有信息列默认为空，这里判断如果为空则表示信息不全，需要提供问题
            if (!isset($userinfo[$element_name->field_name])) {
                return JSONHelper::ERROR_EVALUATE_NOINFO;
            }
        }


//        $userinfo = $userinfo + $userreportinfo;
        return $userinfo;
    }

    public function getEvaluateDateTime($uid)
    {
        $ret = B2bUserQuestionResult::model()->findByAttributes(array("uid" => $uid));
        if ($ret === null) {
            return null;
        }
        return $ret->update_at;
    }

    /**
     * 获取体检报告的个人信息
     */
    public function getUserReportInfo($uid)
    {
        //获取最新的体检报告
        $ret = EvaluateDiseaseElement::model()->findAllByAttributes(
            array("type" => EvaluateDiseaseElement::TYPEREPORT), array("select" => "field_name,name"));
        $keys = array();
        foreach ($ret as $it) {
            $k['field_name'] = $it->field_name;
            $k['name'] = $it->name;
            array_push($keys, $k);
        }
        //从体检报告服务类调取需要的体检报告参数
        $report = new ReportService();
        $reportvalue = $report->getValueByEles($uid, $keys, array(EvaluateReportLog::TYPE_FXPG));
//        $userreportinfo = array();
//        foreach ($reportvalue as $key => $it) {
//            $userreportinfo[$key] = $it["issue"];
//        }
        return $reportvalue;
    }
}
